#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      shoo
#
# Created:     11/06/2011
# Copyright:   (c) shoo 2011
# Licence:     <your licence>
#-------------------------------------------------------------------------------

import urllib, urllib2, Cookie
from google.appengine.api import urlfetch

# App Engine用 httpクライアント
# urllib2ではうまく扱えないcookieを処理できる
class UrlOpener:
    def __init__(self):
        self.cookie = Cookie.SimpleCookie()

    def open(self, url, headers, data = None):
        if data is None:
            method = urlfetch.GET
        else:
            method = urlfetch.POST

        while url is not None:
            response = urlfetch.fetch(url=url,
                          payload=data,
                          method=method,
                          headers=self._getHeaders(headers, self.cookie),
                          allow_truncated=False,
                          follow_redirects=False,
                          deadline=10
                          )
            data = None # Next request will be a get, so no need to send the data again.
            method = urlfetch.GET
            self.cookie.load(response.headers.get('set-cookie', '')) # Load the cookies from the response
            url = response.headers.get('location')

        return response

    def _getHeaders(self, headers, cookie):
        headers['Cookie'] =self._makeCookieHeader(cookie)
        return headers

    def _makeCookieHeader(self, cookie):
        cookieHeader = ""
        for value in cookie.values():
            cookieHeader += "%s=%s; " % (value.key, value.value)
        return cookieHeader

def main():
    pass

if __name__ == '__main__':
    main()
